
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_CN">
  <head>
    <meta charset="utf-8" />
    <title>configparser --- 配置文件解析器 &#8212; Python 3.7.8 文档</title>
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <script type="text/javascript" src="../_static/translations.js"></script>
    
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="在 Python 3.7.8 文档 中搜索"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="关于这些文档" href="../about.html" />
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="copyright" title="版权所有" href="../copyright.html" />
    <link rel="next" title="netrc --- netrc 文件处理" href="netrc.html" />
    <link rel="prev" title="csv --- CSV 文件读写" href="csv.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/3/library/configparser.html" />
    
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
    
    
    
    <style>
      @media only screen {
        table.full-width-table {
            width: 100%;
        }
      }
    </style>
 

  </head><body>
  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="netrc.html" title="netrc --- netrc 文件处理"
             accesskey="N">下一页</a> |</li>
        <li class="right" >
          <a href="csv.html" title="csv --- CSV 文件读写"
             accesskey="P">上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="fileformats.html" accesskey="U">文件格式</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-configparser">
<span id="configparser-configuration-file-parser"></span><h1><a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">configparser</span></code></a> --- 配置文件解析器<a class="headerlink" href="#module-configparser" title="永久链接至标题">¶</a></h1>
<p><strong>源代码:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.7/Lib/configparser.py">Lib/configparser.py</a></p>
<hr class="docutils" id="index-0" />
<p>此模块提供了它实现一种基本配置语言 <a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> 类，这种语言所提供的结构与 Microsoft Windows INI 文件的类似。 你可以使用这种语言来编写能够由最终用户来自定义的 Python 程序。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>这个库 <em>并不</em> 能够解析或写入在 Windows Registry 扩展版本 INI 语法中所使用的值-类型前缀。</p>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<dl class="simple">
<dt>模块 <a class="reference internal" href="shlex.html#module-shlex" title="shlex: Simple lexical analysis for Unix shell-like languages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shlex</span></code></a></dt><dd><p>支持创建可被用作应用配置文件的替代的 Unix 终端式微语言。</p>
</dd>
<dt>模块 <a class="reference internal" href="json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a></dt><dd><p>json 模块实现了一个 JavaScript 语法的子集，它也可被用于这种目的。</p>
</dd>
</dl>
</div>
<div class="section" id="quick-start">
<h2>快速起步<a class="headerlink" href="#quick-start" title="永久链接至标题">¶</a></h2>
<p>让我们准备一个非常基本的配置文件，它看起来是这样的:</p>
<div class="highlight-ini notranslate"><div class="highlight"><pre><span></span><span class="k">[DEFAULT]</span>
<span class="na">ServerAliveInterval</span> <span class="o">=</span> <span class="s">45</span>
<span class="na">Compression</span> <span class="o">=</span> <span class="s">yes</span>
<span class="na">CompressionLevel</span> <span class="o">=</span> <span class="s">9</span>
<span class="na">ForwardX11</span> <span class="o">=</span> <span class="s">yes</span>

<span class="k">[bitbucket.org]</span>
<span class="na">User</span> <span class="o">=</span> <span class="s">hg</span>

<span class="k">[topsecret.server.com]</span>
<span class="na">Port</span> <span class="o">=</span> <span class="s">50022</span>
<span class="na">ForwardX11</span> <span class="o">=</span> <span class="s">no</span>
</pre></div>
</div>
<p>INI 文件的结构描述见 <a class="reference external" href="#supported-ini-file-structure">以下章节</a>。 总的来说，这种文件由多个节组成，每个节包含多个带有值的键。 <a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">configparser</span></code></a> 类可以读取和写入这种文件。 让我们先通过程序方式来创建上述的配置文件。</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">configparser</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="p">[</span><span class="s1">&#39;DEFAULT&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;ServerAliveInterval&#39;</span><span class="p">:</span> <span class="s1">&#39;45&#39;</span><span class="p">,</span>
<span class="gp">... </span>                     <span class="s1">&#39;Compression&#39;</span><span class="p">:</span> <span class="s1">&#39;yes&#39;</span><span class="p">,</span>
<span class="gp">... </span>                     <span class="s1">&#39;CompressionLevel&#39;</span><span class="p">:</span> <span class="s1">&#39;9&#39;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="p">[</span><span class="s1">&#39;bitbucket.org&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="p">{}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="p">[</span><span class="s1">&#39;bitbucket.org&#39;</span><span class="p">][</span><span class="s1">&#39;User&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;hg&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="p">[</span><span class="s1">&#39;topsecret.server.com&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="p">{}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">topsecret</span> <span class="o">=</span> <span class="n">config</span><span class="p">[</span><span class="s1">&#39;topsecret.server.com&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">topsecret</span><span class="p">[</span><span class="s1">&#39;Port&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;50022&#39;</span>     <span class="c1"># mutates the parser</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">topsecret</span><span class="p">[</span><span class="s1">&#39;ForwardX11&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;no&#39;</span>  <span class="c1"># same here</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="p">[</span><span class="s1">&#39;DEFAULT&#39;</span><span class="p">][</span><span class="s1">&#39;ForwardX11&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;yes&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;example.ini&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">configfile</span><span class="p">:</span>
<span class="gp">... </span>  <span class="n">config</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">configfile</span><span class="p">)</span>
<span class="gp">...</span>
</pre></div>
</div>
<p>如你所见，我们可以把配置解析器当作一个字典来处理。 两者确实存在差异，<a class="reference external" href="#mapping-protocol-access">将在后文说明</a>，但是其行为非常接近于字典所具有一般行为。</p>
<p>现在我们已经创建并保存了一个配置文件，让我们再将它读取出来并探究其中包含的数据。</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">config</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="o">.</span><span class="n">sections</span><span class="p">()</span>
<span class="go">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="s1">&#39;example.ini&#39;</span><span class="p">)</span>
<span class="go">[&#39;example.ini&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="o">.</span><span class="n">sections</span><span class="p">()</span>
<span class="go">[&#39;bitbucket.org&#39;, &#39;topsecret.server.com&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;bitbucket.org&#39;</span> <span class="ow">in</span> <span class="n">config</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;bytebong.com&#39;</span> <span class="ow">in</span> <span class="n">config</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="p">[</span><span class="s1">&#39;bitbucket.org&#39;</span><span class="p">][</span><span class="s1">&#39;User&#39;</span><span class="p">]</span>
<span class="go">&#39;hg&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="p">[</span><span class="s1">&#39;DEFAULT&#39;</span><span class="p">][</span><span class="s1">&#39;Compression&#39;</span><span class="p">]</span>
<span class="go">&#39;yes&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">topsecret</span> <span class="o">=</span> <span class="n">config</span><span class="p">[</span><span class="s1">&#39;topsecret.server.com&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">topsecret</span><span class="p">[</span><span class="s1">&#39;ForwardX11&#39;</span><span class="p">]</span>
<span class="go">&#39;no&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">topsecret</span><span class="p">[</span><span class="s1">&#39;Port&#39;</span><span class="p">]</span>
<span class="go">&#39;50022&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">config</span><span class="p">[</span><span class="s1">&#39;bitbucket.org&#39;</span><span class="p">]:</span>  
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
<span class="go">user</span>
<span class="go">compressionlevel</span>
<span class="go">serveraliveinterval</span>
<span class="go">compression</span>
<span class="go">forwardx11</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="p">[</span><span class="s1">&#39;bitbucket.org&#39;</span><span class="p">][</span><span class="s1">&#39;ForwardX11&#39;</span><span class="p">]</span>
<span class="go">&#39;yes&#39;</span>
</pre></div>
</div>
<p>正如我们在上面所看到的，相关的 API 相当直观。 唯一有些神奇的地方是 <code class="docutils literal notranslate"><span class="pre">DEFAULT</span></code> 小节，它为所有其他小节提供了默认值 <a class="footnote-reference brackets" href="#id14" id="id1">1</a>。 还要注意小节中的键大小写不敏感并且会存储为小写形式 <a class="footnote-reference brackets" href="#id14" id="id2">1</a>。</p>
</div>
<div class="section" id="supported-datatypes">
<h2>支持的数据类型<a class="headerlink" href="#supported-datatypes" title="永久链接至标题">¶</a></h2>
<p>配置解析器并不会猜测配置文件中值的类型，而总是将它们在内部存储为字符串。 这意味着如果你需要其他数据类型，你应当自己来转换:</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="p">(</span><span class="n">topsecret</span><span class="p">[</span><span class="s1">&#39;Port&#39;</span><span class="p">])</span>
<span class="go">50022</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">float</span><span class="p">(</span><span class="n">topsecret</span><span class="p">[</span><span class="s1">&#39;CompressionLevel&#39;</span><span class="p">])</span>
<span class="go">9.0</span>
</pre></div>
</div>
<p>由于这种任务十分常用，配置解析器提供了一系列便捷的获取方法来处理整数、浮点数和布尔值。 最后一个类型的处理最为有趣，因为简单地将值传给 <code class="docutils literal notranslate"><span class="pre">bool()</span></code> 是没有用的，<code class="docutils literal notranslate"><span class="pre">bool('False')</span></code> 仍然会是 <code class="docutils literal notranslate"><span class="pre">True</span></code>。 为解决这个问题配置解析器还提供了 <a class="reference internal" href="#configparser.ConfigParser.getboolean" title="configparser.ConfigParser.getboolean"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getboolean()</span></code></a>。 这个方法对大小写不敏感并可识别 <code class="docutils literal notranslate"><span class="pre">'yes'</span></code>/<code class="docutils literal notranslate"><span class="pre">'no'</span></code>, <code class="docutils literal notranslate"><span class="pre">'on'</span></code>/<code class="docutils literal notranslate"><span class="pre">'off'</span></code>, <code class="docutils literal notranslate"><span class="pre">'true'</span></code>/<code class="docutils literal notranslate"><span class="pre">'false'</span></code> 和 <code class="docutils literal notranslate"><span class="pre">'1'</span></code>/<code class="docutils literal notranslate"><span class="pre">'0'</span></code> <a class="footnote-reference brackets" href="#id14" id="id3">1</a> 等布尔值。 例如:</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">topsecret</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s1">&#39;ForwardX11&#39;</span><span class="p">)</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="p">[</span><span class="s1">&#39;bitbucket.org&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s1">&#39;ForwardX11&#39;</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s1">&#39;bitbucket.org&#39;</span><span class="p">,</span> <span class="s1">&#39;Compression&#39;</span><span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
<p>除了 <a class="reference internal" href="#configparser.ConfigParser.getboolean" title="configparser.ConfigParser.getboolean"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getboolean()</span></code></a>，配置解析器还提供了同类的 <a class="reference internal" href="#configparser.ConfigParser.getint" title="configparser.ConfigParser.getint"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getint()</span></code></a> 和 <a class="reference internal" href="#configparser.ConfigParser.getfloat" title="configparser.ConfigParser.getfloat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getfloat()</span></code></a> 方法。 你可以注册你自己的转换器并或是定制已提供的转换器。 <a class="footnote-reference brackets" href="#id14" id="id4">1</a></p>
</div>
<div class="section" id="fallback-values">
<h2>回退值<a class="headerlink" href="#fallback-values" title="永久链接至标题">¶</a></h2>
<p>与字典类似，你可以使用某个小节的 <code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code> 方法来提供回退值:</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">topsecret</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Port&#39;</span><span class="p">)</span>
<span class="go">&#39;50022&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">topsecret</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;CompressionLevel&#39;</span><span class="p">)</span>
<span class="go">&#39;9&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">topsecret</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Cipher&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">topsecret</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Cipher&#39;</span><span class="p">,</span> <span class="s1">&#39;3des-cbc&#39;</span><span class="p">)</span>
<span class="go">&#39;3des-cbc&#39;</span>
</pre></div>
</div>
<p>请注意默认值会优先于回退值。 例如，在我们的示例中 <code class="docutils literal notranslate"><span class="pre">'CompressionLevel'</span></code> 键仅在 <code class="docutils literal notranslate"><span class="pre">'DEFAULT'</span></code> 小节被指定。 如果你尝试在 <code class="docutils literal notranslate"><span class="pre">'topsecret.server.com'</span></code> 小节获取它，我们将总是获取到默认值，即使我们指定了一个回退值:</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">topsecret</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;CompressionLevel&#39;</span><span class="p">,</span> <span class="s1">&#39;3&#39;</span><span class="p">)</span>
<span class="go">&#39;9&#39;</span>
</pre></div>
</div>
<p>还需要注意的一点是解析器层级的 <code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code> 方法提供了自定义的更复杂接口，它被维护用于向下兼容。 当使用此方法时，回退值可以通过 <code class="docutils literal notranslate"><span class="pre">fallback</span></code> 仅限关键字参数来提供:</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;bitbucket.org&#39;</span><span class="p">,</span> <span class="s1">&#39;monster&#39;</span><span class="p">,</span>
<span class="gp">... </span>           <span class="n">fallback</span><span class="o">=</span><span class="s1">&#39;No such things as monsters&#39;</span><span class="p">)</span>
<span class="go">&#39;No such things as monsters&#39;</span>
</pre></div>
</div>
<p>同样的 <code class="docutils literal notranslate"><span class="pre">fallback</span></code> 参数也可在 <a class="reference internal" href="#configparser.ConfigParser.getint" title="configparser.ConfigParser.getint"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getint()</span></code></a>, <a class="reference internal" href="#configparser.ConfigParser.getfloat" title="configparser.ConfigParser.getfloat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getfloat()</span></code></a> 和 <a class="reference internal" href="#configparser.ConfigParser.getboolean" title="configparser.ConfigParser.getboolean"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getboolean()</span></code></a> 方法中使用，例如:</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;BatchMode&#39;</span> <span class="ow">in</span> <span class="n">topsecret</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">topsecret</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s1">&#39;BatchMode&#39;</span><span class="p">,</span> <span class="n">fallback</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="p">[</span><span class="s1">&#39;DEFAULT&#39;</span><span class="p">][</span><span class="s1">&#39;BatchMode&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;no&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">topsecret</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s1">&#39;BatchMode&#39;</span><span class="p">,</span> <span class="n">fallback</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">False</span>
</pre></div>
</div>
</div>
<div class="section" id="supported-ini-file-structure">
<h2>受支持的 INI 文件结构<a class="headerlink" href="#supported-ini-file-structure" title="永久链接至标题">¶</a></h2>
<p>配置文件是由小节组成的，每个小节都有一个 <code class="docutils literal notranslate"><span class="pre">[section]</span></code> 标头，加上多个由特定字符串 (默认为 <code class="docutils literal notranslate"><span class="pre">=</span></code> 或 <code class="docutils literal notranslate"><span class="pre">:</span></code> <a class="footnote-reference brackets" href="#id14" id="id5">1</a>) 分隔的键/值条目。 默认情况下小节名对大小写敏感而键对大小写不敏感 <a class="footnote-reference brackets" href="#id14" id="id6">1</a>。 键和值开头和末尾的空格会被移除。 值可以被省略，在此情况下键/值分隔符也可以被省略。 值还可以跨越多行，只要其他行带有比值的第一行更深的缩进。 依据解析器的具体模式，空白行可能被视为多行值的组成部分也可能被忽略。</p>
<p>配置文件可以包含注释，要带有指定字符前缀 (默认为 <code class="docutils literal notranslate"><span class="pre">#</span></code> 和 <code class="docutils literal notranslate"><span class="pre">;</span></code> <a class="footnote-reference brackets" href="#id14" id="id7">1</a>)。 注释可以单独出现于原本的空白行，并可使用缩进。 <a class="footnote-reference brackets" href="#id14" id="id8">1</a></p>
<p>例如:</p>
<div class="highlight-ini notranslate"><div class="highlight"><pre><span></span><span class="k">[Simple Values]</span>
<span class="na">key</span><span class="o">=</span><span class="s">value</span>
<span class="na">spaces in keys</span><span class="o">=</span><span class="s">allowed</span>
<span class="na">spaces in values</span><span class="o">=</span><span class="s">allowed as well</span>
<span class="na">spaces around the delimiter</span> <span class="o">=</span> <span class="s">obviously</span>
<span class="na">you can also use : to delimit keys from values</span>

<span class="k">[All Values Are Strings]</span>
<span class="na">values like this: 1000000</span>
<span class="na">or this: 3.14159265359</span>
<span class="na">are they treated as numbers? : no</span>
<span class="na">integers, floats and booleans are held as: strings</span>
<span class="na">can use the API to get converted values directly: true</span>

<span class="k">[Multiline Values]</span>
<span class="na">chorus: I&#39;m a lumberjack, and I&#39;m okay</span>
    <span class="na">I sleep all night and I work all day</span>

<span class="k">[No Values]</span>
<span class="na">key_without_value</span>
<span class="na">empty string value here</span> <span class="o">=</span>

<span class="k">[You can use comments]</span>
<span class="c1"># like this</span>
<span class="c1">; or this</span>

<span class="c1"># By default only in an empty line.</span>
<span class="c1"># Inline comments can be harmful because they prevent users</span>
<span class="c1"># from using the delimiting characters as parts of values.</span>
<span class="c1"># That being said, this can be customized.</span>

    <span class="k">[Sections Can Be Indented]</span>
        <span class="na">can_values_be_as_well</span> <span class="o">=</span> <span class="s">True</span>
<span class="s">        does_that_mean_anything_special = False</span>
<span class="s">        purpose = formatting for readability</span>
<span class="s">        multiline_values = are</span>
<span class="s">            handled just fine as</span>
<span class="s">            long as they are indented</span>
<span class="s">            deeper than the first line</span>
<span class="s">            of a value</span>
<span class="s">        # Did I mention we can indent comments, too?</span>
</pre></div>
</div>
</div>
<div class="section" id="interpolation-of-values">
<h2>值的插入<a class="headerlink" href="#interpolation-of-values" title="永久链接至标题">¶</a></h2>
<p>在核心功能之上，<a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> 还支持插值。 这意味着值可以在被 <code class="docutils literal notranslate"><span class="pre">get()</span></code> 调用返回之前进行预处理。</p>
<span class="target" id="index-1"></span><dl class="class">
<dt id="configparser.BasicInterpolation">
<em class="property">class </em><code class="sig-prename descclassname">configparser.</code><code class="sig-name descname">BasicInterpolation</code><a class="headerlink" href="#configparser.BasicInterpolation" title="永久链接至目标">¶</a></dt>
<dd><p>默认实现由 <a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> 来使用。 它允许值包含引用了相同小节中其他值或者特殊的默认小节中的值的格式字符串 <a class="footnote-reference brackets" href="#id14" id="id9">1</a>。 额外的默认值可以在初始化时提供。</p>
<p>例如:</p>
<div class="highlight-ini notranslate"><div class="highlight"><pre><span></span><span class="k">[Paths]</span>
<span class="na">home_dir: /Users</span>
<span class="na">my_dir: %(home_dir)s/lumberjack</span>
<span class="na">my_pictures: %(my_dir)s/Pictures</span>

<span class="k">[Escape]</span>
<span class="na">gain: 80%%  # use a %% to escape the % sign (% is the only character that needs to be escaped)</span>
</pre></div>
</div>
<p>在上面的例子里，<a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> 的 <em>interpolation</em> 设为 <code class="docutils literal notranslate"><span class="pre">BasicInterpolation()</span></code>，这会将 <code class="docutils literal notranslate"><span class="pre">%(home_dir)s</span></code> 求解为 <code class="docutils literal notranslate"><span class="pre">home_dir</span></code> 的值 (在这里是 <code class="docutils literal notranslate"><span class="pre">/Users</span></code>)。 <code class="docutils literal notranslate"><span class="pre">%(my_dir)s</span></code> 的将被实际求解为 <code class="docutils literal notranslate"><span class="pre">/Users/lumberjack</span></code>。 所有插值都是按需进行的，这样引用链中使用的键不必以任何特定顺序在配置文件中指明。</p>
<p>当 <code class="docutils literal notranslate"><span class="pre">interpolation</span></code> 设为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 时，解析器会简单地返回 <code class="docutils literal notranslate"><span class="pre">%(my_dir)s/Pictures</span></code> 作为 <code class="docutils literal notranslate"><span class="pre">my_pictures</span></code> 的值，并返回 <code class="docutils literal notranslate"><span class="pre">%(home_dir)s/lumberjack</span></code> 作为 <code class="docutils literal notranslate"><span class="pre">my_dir</span></code> 的值。</p>
</dd></dl>

<span class="target" id="index-2"></span><dl class="class">
<dt id="configparser.ExtendedInterpolation">
<em class="property">class </em><code class="sig-prename descclassname">configparser.</code><code class="sig-name descname">ExtendedInterpolation</code><a class="headerlink" href="#configparser.ExtendedInterpolation" title="永久链接至目标">¶</a></dt>
<dd><p>一个用于插值的替代处理程序实现了更高级的语法，它被用于 <code class="docutils literal notranslate"><span class="pre">zc.buildout</span></code> 中的实例。 扩展插值使用 <code class="docutils literal notranslate"><span class="pre">${section:option}</span></code> 来表示来自外部小节的值。 插值可以跨越多个层级。 为了方便使用，<code class="docutils literal notranslate"><span class="pre">section:</span></code> 部分可被省略，插值会默认作用于当前小节（可能会从特殊小节获取默认值）。</p>
<p>例如，上面使用基本插值描述的配置，使用扩展插值将是这个样子:</p>
<div class="highlight-ini notranslate"><div class="highlight"><pre><span></span><span class="k">[Paths]</span>
<span class="na">home_dir: /Users</span>
<span class="na">my_dir: ${home_dir}/lumberjack</span>
<span class="na">my_pictures: ${my_dir}/Pictures</span>

<span class="k">[Escape]</span>
<span class="na">cost: $$80  # use a $$ to escape the $ sign ($ is the only character that needs to be escaped)</span>
</pre></div>
</div>
<p>来自其他小节的值也可以被获取:</p>
<div class="highlight-ini notranslate"><div class="highlight"><pre><span></span><span class="k">[Common]</span>
<span class="na">home_dir: /Users</span>
<span class="na">library_dir: /Library</span>
<span class="na">system_dir: /System</span>
<span class="na">macports_dir: /opt/local</span>

<span class="k">[Frameworks]</span>
<span class="na">Python: 3.2</span>
<span class="na">path: ${Common:system_dir}/Library/Frameworks/</span>

<span class="k">[Arthur]</span>
<span class="na">nickname: Two Sheds</span>
<span class="na">last_name: Jackson</span>
<span class="na">my_dir: ${Common:home_dir}/twosheds</span>
<span class="na">my_pictures: ${my_dir}/Pictures</span>
<span class="na">python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="mapping-protocol-access">
<h2>映射协议访问<a class="headerlink" href="#mapping-protocol-access" title="永久链接至标题">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
<p>映射协议访问这个通用名称是指允许以字典的方式来使用自定义对象的功能。 在 <a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">configparser</span></code></a> 中，映射接口的实现使用了 <code class="docutils literal notranslate"><span class="pre">parser['section']['option']</span></code> 标记法。</p>
<p><code class="docutils literal notranslate"><span class="pre">parser['section']</span></code> 专门为解析器中的小节数据返回一个代理。 这意味着其中的值不会被拷贝，而是在需要时从原始解析器中获取。 更为重要的是，当值在小节代理上被修改时，它们其实是在原始解析器中发生了改变。</p>
<p><a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">configparser</span></code></a> 对象的行为会尽可能地接近真正的字典。 映射接口是完整而且遵循 <a class="reference internal" href="collections.abc.html#collections.abc.MutableMapping" title="collections.abc.MutableMapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableMapping</span></code></a> ABC 规范的。 但是，还是有一些差异应当被纳入考虑:</p>
<ul>
<li><p>默认情况下，小节中的所有键是以大小写不敏感的方式来访问的 <a class="footnote-reference brackets" href="#id14" id="id10">1</a>。 例如 <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">option</span> <span class="pre">in</span> <span class="pre">parser[&quot;section&quot;]</span></code> 只会产生 <code class="docutils literal notranslate"><span class="pre">optionxform</span></code> 形式的选项键名称。 也就是说默认使用小写字母键名。 与此同时，对于一个包含键 <code class="docutils literal notranslate"><span class="pre">'a'</span></code> 的小节，以下两个表达式均将返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;a&quot;</span> <span class="ow">in</span> <span class="n">parser</span><span class="p">[</span><span class="s2">&quot;section&quot;</span><span class="p">]</span>
<span class="s2">&quot;A&quot;</span> <span class="ow">in</span> <span class="n">parser</span><span class="p">[</span><span class="s2">&quot;section&quot;</span><span class="p">]</span>
</pre></div>
</div>
</li>
<li><p>所有小节也包括 <code class="docutils literal notranslate"><span class="pre">DEFAULTSECT</span></code>，这意味着对一个小节执行 <code class="docutils literal notranslate"><span class="pre">.clear()</span></code> 可能无法使得该小节显示为空。 这是因为默认值是无法从小节中被删除的（因为从技术上说它们并不在那里）。 如果它们在小节中被覆盖，删除将导致默认值重新变为可见。 尝试删除默认值将会引发 <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>。</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">DEFAULTSECT</span></code> 无法从解析器中被移除:</p>
<ul class="simple">
<li><p>尝试删除将引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>，</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">parser.clear()</span></code> 会保留其原状，</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">parser.popitem()</span></code> 绝不会将其返回。</p></li>
</ul>
</li>
<li><p><code class="docutils literal notranslate"><span class="pre">parser.get(section,</span> <span class="pre">option,</span> <span class="pre">**kwargs)</span></code> - 第二个参数 <strong>并非</strong> 回退值。 但是请注意小节层级的 <code class="docutils literal notranslate"><span class="pre">get()</span></code> 方法可同时兼容映射协议和经典配置解析器 API。</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">parser.items()</span></code> 兼容映射协议（返回 <em>section_name</em>, <em>section_proxy</em> 对的列表，包括 DEFAULTSECT）。 但是，此方法也可以带参数发起调用: <code class="docutils literal notranslate"><span class="pre">parser.items(section,</span> <span class="pre">raw,</span> <span class="pre">vars)</span></code>。 这种调用形式返回指定 <code class="docutils literal notranslate"><span class="pre">section</span></code> 的 <em>option</em>, <em>value</em> 对的列表，将展开所有插值（除非提供了 <code class="docutils literal notranslate"><span class="pre">raw=True</span></code> 选项）。</p></li>
</ul>
<p>映射协议是在现有的传统 API 之上实现的，以便重载原始接口的子类仍然具有符合预期的有效映射。</p>
</div>
<div class="section" id="customizing-parser-behaviour">
<h2>定制解析器行为<a class="headerlink" href="#customizing-parser-behaviour" title="永久链接至标题">¶</a></h2>
<p>INI 格式的变种数量几乎和使用此格式的应用一样多。 <a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">configparser</span></code></a> 花费了很大力气来为尽量大范围的可用 INI 样式提供支持。 默认的可用功能主要由历史状况来确定，你很可能会想要定制某些特性。</p>
<p>改变特定配置解析器行为的最常见方式是使用 <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> 选项:</p>
<ul>
<li><p><em>defaults</em>，默认值: <code class="docutils literal notranslate"><span class="pre">None</span></code></p>
<p>此选项接受一个键值对的字典，它将被首先放入 <code class="docutils literal notranslate"><span class="pre">DEFAULT</span></code> 小节。 这实现了一种优雅的方式来支持简洁的配置文件，它不必指定与已记录的默认值相同的值。</p>
<p>提示：如果你想要为特定的小节指定默认的值，请在读取实际文件之前使用 <code class="xref py py-meth docutils literal notranslate"><span class="pre">read_dict()</span></code>。</p>
</li>
<li><p><em>dict_type</em>，默认值: <a class="reference internal" href="collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.OrderedDict</span></code></a></p>
<p>此选项主要影响映射协议的行为和写入配置文件的外观。 使用默认的有序字典时，每个小节是按照它们被加入解析器的顺序保存的。 在小节内的选项也是如此。</p>
<p>还有其他替换的字典类型可用，例如在写回数据时对小节和选项进行排序。 你也可以出于性能原因而使用普通字典。</p>
<p>请注意：也有办法通过单次操作来添加一组键值对。 当你在这些操作中使用一个常规字典时，键将按顺序进行排列，因为 dict 类型从 Python 3.7 起将会保留插入顺序。 例如:</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">read_dict</span><span class="p">({</span><span class="s1">&#39;section1&#39;</span><span class="p">:</span> <span class="p">{</span><span class="s1">&#39;key1&#39;</span><span class="p">:</span> <span class="s1">&#39;value1&#39;</span><span class="p">,</span>
<span class="gp">... </span>                               <span class="s1">&#39;key2&#39;</span><span class="p">:</span> <span class="s1">&#39;value2&#39;</span><span class="p">,</span>
<span class="gp">... </span>                               <span class="s1">&#39;key3&#39;</span><span class="p">:</span> <span class="s1">&#39;value3&#39;</span><span class="p">},</span>
<span class="gp">... </span>                  <span class="s1">&#39;section2&#39;</span><span class="p">:</span> <span class="p">{</span><span class="s1">&#39;keyA&#39;</span><span class="p">:</span> <span class="s1">&#39;valueA&#39;</span><span class="p">,</span>
<span class="gp">... </span>                               <span class="s1">&#39;keyB&#39;</span><span class="p">:</span> <span class="s1">&#39;valueB&#39;</span><span class="p">,</span>
<span class="gp">... </span>                               <span class="s1">&#39;keyC&#39;</span><span class="p">:</span> <span class="s1">&#39;valueC&#39;</span><span class="p">},</span>
<span class="gp">... </span>                  <span class="s1">&#39;section3&#39;</span><span class="p">:</span> <span class="p">{</span><span class="s1">&#39;foo&#39;</span><span class="p">:</span> <span class="s1">&#39;x&#39;</span><span class="p">,</span>
<span class="gp">... </span>                               <span class="s1">&#39;bar&#39;</span><span class="p">:</span> <span class="s1">&#39;y&#39;</span><span class="p">,</span>
<span class="gp">... </span>                               <span class="s1">&#39;baz&#39;</span><span class="p">:</span> <span class="s1">&#39;z&#39;</span><span class="p">}</span>
<span class="gp">... </span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">sections</span><span class="p">()</span>
<span class="go">[&#39;section1&#39;, &#39;section2&#39;, &#39;section3&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">option</span> <span class="k">for</span> <span class="n">option</span> <span class="ow">in</span> <span class="n">parser</span><span class="p">[</span><span class="s1">&#39;section3&#39;</span><span class="p">]]</span>
<span class="go">[&#39;foo&#39;, &#39;bar&#39;, &#39;baz&#39;]</span>
</pre></div>
</div>
</li>
<li><p><em>allow_no_value</em>，默认值: <code class="docutils literal notranslate"><span class="pre">False</span></code></p>
<p>已知某些配置文件会包括不带值的设置，但其在其他方面均符合 <a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">configparser</span></code></a> 所支持的语法。 构造器的 <em>allow_no_value</em> 形参可用于指明应当接受这样的值:</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">configparser</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">sample_config</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;</span>
<span class="gp">... </span><span class="s2">[mysqld]</span>
<span class="gp">... </span><span class="s2">  user = mysql</span>
<span class="gp">... </span><span class="s2">  pid-file = /var/run/mysqld/mysqld.pid</span>
<span class="gp">... </span><span class="s2">  skip-external-locking</span>
<span class="gp">... </span><span class="s2">  old_passwords = 1</span>
<span class="gp">... </span><span class="s2">  skip-bdb</span>
<span class="gp">... </span><span class="s2">  # we don&#39;t need ACID today</span>
<span class="gp">... </span><span class="s2">  skip-innodb</span>
<span class="gp">... </span><span class="s2">&quot;&quot;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">(</span><span class="n">allow_no_value</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="o">.</span><span class="n">read_string</span><span class="p">(</span><span class="n">sample_config</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Settings with values are treated as before:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="p">[</span><span class="s2">&quot;mysqld&quot;</span><span class="p">][</span><span class="s2">&quot;user&quot;</span><span class="p">]</span>
<span class="go">&#39;mysql&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Settings without values provide None:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="p">[</span><span class="s2">&quot;mysqld&quot;</span><span class="p">][</span><span class="s2">&quot;skip-bdb&quot;</span><span class="p">]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Settings which aren&#39;t specified still raise an error:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="p">[</span><span class="s2">&quot;mysqld&quot;</span><span class="p">][</span><span class="s2">&quot;does-not-exist&quot;</span><span class="p">]</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">KeyError</span>: <span class="n">&#39;does-not-exist&#39;</span>
</pre></div>
</div>
</li>
<li><p><em>delimiters</em>，默认值: <code class="docutils literal notranslate"><span class="pre">('=',</span> <span class="pre">':')</span></code></p>
<p>分隔符是用于在小节内分隔键和值的子字符串。 在一行中首次出现的分隔子字符串会被视为一个分隔符。 这意味着值可以包含分隔符（但键不可以）。</p>
<p>另请参见 <a class="reference internal" href="#configparser.ConfigParser.write" title="configparser.ConfigParser.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ConfigParser.write()</span></code></a> 的 <em>space_around_delimiters</em> 参数。</p>
</li>
<li><p><em>comment_prefixes</em>，默认值: <code class="docutils literal notranslate"><span class="pre">('#',</span> <span class="pre">';')</span></code></p></li>
<li><p><em>inline_comment_prefixes</em>，默认值: <code class="docutils literal notranslate"><span class="pre">None</span></code></p>
<p>注释前缀是配置文件中用于标示一条有效注释的开头的字符串。 <em>comment_prefixes</em> 仅用在被视为空白的行（可以缩进）之前而 <em>inline_comment_prefixes</em> 可用在每个有效值之后（例如小节名称、选项以及空白的行）。 默认情况下禁用行内注释，并且 <code class="docutils literal notranslate"><span class="pre">'#'</span></code> 和 <code class="docutils literal notranslate"><span class="pre">';'</span></code> 都被用作完整行注释的前缀。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.2 版更改: </span>在之前的 <a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">configparser</span></code></a> 版本中行为匹配 <code class="docutils literal notranslate"><span class="pre">comment_prefixes=('#',';')</span></code> 和 <code class="docutils literal notranslate"><span class="pre">inline_comment_prefixes=(';',)</span></code>。</p>
</div>
<p>请注意配置解析器不支持对注释前缀的转义，因此使用 <em>inline_comment_prefixes</em> 可能妨碍用户将被用作注释前缀的字符指定为可选值。 当有疑问时，请避免设置 <em>inline_comment_prefixes</em>。 在许多情况下，在多行值的一行开头存储注释前缀字符的唯一方式是进行前缀插值，例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">configparser</span> <span class="kn">import</span> <span class="n">ConfigParser</span><span class="p">,</span> <span class="n">ExtendedInterpolation</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">ConfigParser</span><span class="p">(</span><span class="n">interpolation</span><span class="o">=</span><span class="n">ExtendedInterpolation</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># the default BasicInterpolation could be used as well</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">read_string</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;</span>
<span class="gp">... </span><span class="s2">[DEFAULT]</span>
<span class="gp">... </span><span class="s2">hash = #</span>
<span class="gp">...</span><span class="s2"></span>
<span class="gp">... </span><span class="s2">[hashes]</span>
<span class="gp">... </span><span class="s2">shebang =</span>
<span class="gp">... </span><span class="s2">  $</span><span class="si">{hash}</span><span class="s2">!/usr/bin/env python</span>
<span class="gp">... </span><span class="s2">  $</span><span class="si">{hash}</span><span class="s2"> -*- coding: utf-8 -*-</span>
<span class="gp">...</span><span class="s2"></span>
<span class="gp">... </span><span class="s2">extensions =</span>
<span class="gp">... </span><span class="s2">  enabled_extension</span>
<span class="gp">... </span><span class="s2">  another_extension</span>
<span class="gp">... </span><span class="s2">  #disabled_by_comment</span>
<span class="gp">... </span><span class="s2">  yet_another_extension</span>
<span class="gp">...</span><span class="s2"></span>
<span class="gp">... </span><span class="s2">interpolation not necessary = if # is not at line start</span>
<span class="gp">... </span><span class="s2">even in multiline values = line #1</span>
<span class="gp">... </span><span class="s2">  line #2</span>
<span class="gp">... </span><span class="s2">  line #3</span>
<span class="gp">... </span><span class="s2">&quot;&quot;&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">parser</span><span class="p">[</span><span class="s1">&#39;hashes&#39;</span><span class="p">][</span><span class="s1">&#39;shebang&#39;</span><span class="p">])</span>

<span class="go">#!/usr/bin/env python</span>
<span class="go"># -*- coding: utf-8 -*-</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">parser</span><span class="p">[</span><span class="s1">&#39;hashes&#39;</span><span class="p">][</span><span class="s1">&#39;extensions&#39;</span><span class="p">])</span>

<span class="go">enabled_extension</span>
<span class="go">another_extension</span>
<span class="go">yet_another_extension</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">parser</span><span class="p">[</span><span class="s1">&#39;hashes&#39;</span><span class="p">][</span><span class="s1">&#39;interpolation not necessary&#39;</span><span class="p">])</span>
<span class="go">if # is not at line start</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">parser</span><span class="p">[</span><span class="s1">&#39;hashes&#39;</span><span class="p">][</span><span class="s1">&#39;even in multiline values&#39;</span><span class="p">])</span>
<span class="go">line #1</span>
<span class="go">line #2</span>
<span class="go">line #3</span>
</pre></div>
</div>
</li>
<li><p><em>strict</em>，默认值: <code class="docutils literal notranslate"><span class="pre">True</span></code></p>
<p>当设为 <code class="docutils literal notranslate"><span class="pre">True</span></code> 时，解析器在从单一源读取 (使用 <code class="xref py py-meth docutils literal notranslate"><span class="pre">read_file()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">read_string()</span></code> 或 <code class="xref py py-meth docutils literal notranslate"><span class="pre">read_dict()</span></code>) 期间将不允许任何小节或选项出现重复。 推荐在新的应用中使用严格解析器。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.2 版更改: </span>在之前的 <a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">configparser</span></code></a> 版本中行为匹配 <code class="docutils literal notranslate"><span class="pre">strict=False</span></code>。</p>
</div>
</li>
<li><p><em>empty_lines_in_values</em>，默认值: <code class="docutils literal notranslate"><span class="pre">True</span></code></p>
<p>在配置解析器中，值可以包含多行，只要它们的缩进级别低于它们所对应的键。 默认情况下解析器还会将空行视为值的一部分。 于此同时，键本身也可以任意缩进以提升可读性。 因此，当配置文件变得非常庞大而复杂时，用户很容易失去对文件结构的掌控。 例如:</p>
<div class="highlight-ini notranslate"><div class="highlight"><pre><span></span><span class="k">[Section]</span>
<span class="na">key</span> <span class="o">=</span> <span class="s">multiline</span>
<span class="s">  value with a gotcha</span>

 <span class="na">this</span> <span class="o">=</span> <span class="s">is still a part of the multiline value of &#39;key&#39;</span>
</pre></div>
</div>
<p>在用户查看时这可能会特别有问题，如果她是使用比例字体来编辑文件的话。 这就是为什么当你的应用不需要带有空行的值时，你应该考虑禁用它们。 这将使得空行每次都会作为键之间的分隔。 在上面的示例中，空行产生了两个键，<code class="docutils literal notranslate"><span class="pre">key</span></code> 和 <code class="docutils literal notranslate"><span class="pre">this</span></code>。</p>
</li>
<li><p><em>default_section</em>，默认值: <code class="docutils literal notranslate"><span class="pre">configparser.DEFAULTSECT</span></code> (即: <code class="docutils literal notranslate"><span class="pre">&quot;DEFAULT&quot;</span></code>)</p>
<p>允许设置一个保存默认值的特殊节在其他节或插值等目的中使用的惯例是这个库所拥有的一个强大概念，使得用户能够创建复杂的声明性配置。 这种特殊节通常称为 <code class="docutils literal notranslate"><span class="pre">&quot;DEFAULT&quot;</span></code> 但也可以被定制为指向任何其他有效的节名称。 一些典型的值包括: <code class="docutils literal notranslate"><span class="pre">&quot;general&quot;</span></code> 或 <code class="docutils literal notranslate"><span class="pre">&quot;common&quot;</span></code>。 所提供的名称在从任意节读取的时候被用于识别默认的节，而且也会在将配置写回文件时被使用。 它的当前值可以使用 <code class="docutils literal notranslate"><span class="pre">parser_instance.default_section</span></code> 属性来获取，并且可以在运行时被修改（即将文件从一种格式转换为另一种格式）。</p>
</li>
<li><p><em>interpolation</em>，默认值: <code class="docutils literal notranslate"><span class="pre">configparser.BasicInterpolation</span></code></p>
<p>插值行为可以用通过提供 <em>interpolation</em> 参数提供自定义处理程序的方式来定制。 <code class="docutils literal notranslate"><span class="pre">None</span></code> 可用来完全禁用插值，<code class="docutils literal notranslate"><span class="pre">ExtendedInterpolation()</span></code> 提供了一种更高级的变体形式，它的设计受到了 <code class="docutils literal notranslate"><span class="pre">zc.buildout</span></code> 的启发。 有关该主题的更多信息请参见 <a class="reference external" href="#interpolation-of-values">专门的文档章节</a>。 <a class="reference internal" href="#configparser.RawConfigParser" title="configparser.RawConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawConfigParser</span></code></a> 具有默认的值 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
</li>
<li><p><em>converters</em>，默认值: 不设置</p>
<p>配置解析器提供了可选的值获取方法用来执行类型转换。 默认实现包括 <a class="reference internal" href="#configparser.ConfigParser.getint" title="configparser.ConfigParser.getint"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getint()</span></code></a>, <a class="reference internal" href="#configparser.ConfigParser.getfloat" title="configparser.ConfigParser.getfloat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getfloat()</span></code></a> 以及 <a class="reference internal" href="#configparser.ConfigParser.getboolean" title="configparser.ConfigParser.getboolean"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getboolean()</span></code></a>。 如果还需要其他获取方法，用户可以在子类中定义它们，或者传入一个字典，其中每个键都是一个转换器的名称而每个值都是一个实现了特定转换的可调用对象。 例如，传入 <code class="docutils literal notranslate"><span class="pre">{'decimal':</span> <span class="pre">decimal.Decimal}</span></code> 将对解释器对象和所有节代理添加 <code class="xref py py-meth docutils literal notranslate"><span class="pre">getdecimal()</span></code>。 换句话说，可以同时编写 <code class="docutils literal notranslate"><span class="pre">parser_instance.getdecimal('section',</span> <span class="pre">'key',</span> <span class="pre">fallback=0)</span></code> 和 <code class="docutils literal notranslate"><span class="pre">parser_instance['section'].getdecimal('key',</span> <span class="pre">0)</span></code>。</p>
<p>如果转换器需要访问解析器的状态，可以在配置解析器子类上作为一个方法来实现。 如果该方法的名称是以 <code class="docutils literal notranslate"><span class="pre">get</span></code> 打头的，它将在所有节代理上以兼容字典的形式提供（参见上面的 <code class="docutils literal notranslate"><span class="pre">getdecimal()</span></code> 示例）。</p>
</li>
</ul>
<p>更多高级定制选项可通过重载这些解析器属性的默认值来达成。 默认值是在类中定义的，因此它们可以通过子类或属性赋值来重载。</p>
<dl class="attribute">
<dt id="configparser.ConfigParser.BOOLEAN_STATES">
<code class="sig-prename descclassname">ConfigParser.</code><code class="sig-name descname">BOOLEAN_STATES</code><a class="headerlink" href="#configparser.ConfigParser.BOOLEAN_STATES" title="永久链接至目标">¶</a></dt>
<dd><p>默认情况下当使用 <a class="reference internal" href="#configparser.ConfigParser.getboolean" title="configparser.ConfigParser.getboolean"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getboolean()</span></code></a> 时，配置解析器会将下列值视为 <code class="docutils literal notranslate"><span class="pre">True</span></code>: <code class="docutils literal notranslate"><span class="pre">'1'</span></code>, <code class="docutils literal notranslate"><span class="pre">'yes'</span></code>, <code class="docutils literal notranslate"><span class="pre">'true'</span></code>, <code class="docutils literal notranslate"><span class="pre">'on'</span></code> 而将下列值视为 <code class="docutils literal notranslate"><span class="pre">False</span></code>: <code class="docutils literal notranslate"><span class="pre">'0'</span></code>, <code class="docutils literal notranslate"><span class="pre">'no'</span></code>, <code class="docutils literal notranslate"><span class="pre">'false'</span></code>, <code class="docutils literal notranslate"><span class="pre">'off'</span></code>。 你可以通过指定一个自定义的字符串键及其对应的布尔值字典来重载此行为。 例如:</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">custom</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">custom</span><span class="p">[</span><span class="s1">&#39;section1&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;funky&#39;</span><span class="p">:</span> <span class="s1">&#39;nope&#39;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">custom</span><span class="p">[</span><span class="s1">&#39;section1&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s1">&#39;funky&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">ValueError</span>: <span class="n">Not a boolean: nope</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">custom</span><span class="o">.</span><span class="n">BOOLEAN_STATES</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;sure&#39;</span><span class="p">:</span> <span class="kc">True</span><span class="p">,</span> <span class="s1">&#39;nope&#39;</span><span class="p">:</span> <span class="kc">False</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">custom</span><span class="p">[</span><span class="s1">&#39;section1&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s1">&#39;funky&#39;</span><span class="p">)</span>
<span class="go">False</span>
</pre></div>
</div>
<p>其他典型的布尔值对包括 <code class="docutils literal notranslate"><span class="pre">accept</span></code>/<code class="docutils literal notranslate"><span class="pre">reject</span></code> 或 <code class="docutils literal notranslate"><span class="pre">enabled</span></code>/<code class="docutils literal notranslate"><span class="pre">disabled</span></code>。</p>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.optionxform">
<code class="sig-prename descclassname">ConfigParser.</code><code class="sig-name descname">optionxform</code><span class="sig-paren">(</span><em class="sig-param">option</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.optionxform" title="永久链接至目标">¶</a></dt>
<dd><p>这个方法会转换每次 read, get, 或 set 操作的选项名称。 默认会将名称转换为小写形式。 这也意味着当一个配置文件被写入时，所有键都将为小写形式。 如果此行为不合适则要重载此方法。 例如:</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">config</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;</span>
<span class="gp">... </span><span class="s2">[Section1]</span>
<span class="gp">... </span><span class="s2">Key = Value</span>
<span class="gp">...</span><span class="s2"></span>
<span class="gp">... </span><span class="s2">[Section2]</span>
<span class="gp">... </span><span class="s2">AnotherKey = Value</span>
<span class="gp">... </span><span class="s2">&quot;&quot;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">typical</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">typical</span><span class="o">.</span><span class="n">read_string</span><span class="p">(</span><span class="n">config</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">typical</span><span class="p">[</span><span class="s1">&#39;Section1&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
<span class="go">[&#39;key&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">typical</span><span class="p">[</span><span class="s1">&#39;Section2&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
<span class="go">[&#39;anotherkey&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">custom</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">RawConfigParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">custom</span><span class="o">.</span><span class="n">optionxform</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">option</span><span class="p">:</span> <span class="n">option</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">custom</span><span class="o">.</span><span class="n">read_string</span><span class="p">(</span><span class="n">config</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">custom</span><span class="p">[</span><span class="s1">&#39;Section1&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
<span class="go">[&#39;Key&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">custom</span><span class="p">[</span><span class="s1">&#39;Section2&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
<span class="go">[&#39;AnotherKey&#39;]</span>
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>optionxform 函数会将选项名称转换为规范形式。 这应该是一个幂等函数：如果名称已经为规范形式，则应不加修改地将其返回。</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="configparser.ConfigParser.SECTCRE">
<code class="sig-prename descclassname">ConfigParser.</code><code class="sig-name descname">SECTCRE</code><a class="headerlink" href="#configparser.ConfigParser.SECTCRE" title="永久链接至目标">¶</a></dt>
<dd><p>一个已编译正则表达式会被用来解析节标头。 默认将 <code class="docutils literal notranslate"><span class="pre">[section]</span></code> 匹配到名称 <code class="docutils literal notranslate"><span class="pre">&quot;section&quot;</span></code>。 空格会被视为节名称的一部分，因此 <code class="docutils literal notranslate"><span class="pre">[</span>&#160; <span class="pre">larch</span>&#160; <span class="pre">]</span></code> 将被读取为一个名称为 <code class="docutils literal notranslate"><span class="pre">&quot;</span>&#160; <span class="pre">larch</span>&#160; <span class="pre">&quot;</span></code> 的节。 如果此行为不合适则要重载此属性。 例如:</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;</span>
<span class="gp">... </span><span class="s2">[Section 1]</span>
<span class="gp">... </span><span class="s2">option = value</span>
<span class="gp">...</span><span class="s2"></span>
<span class="gp">... </span><span class="s2">[  Section 2  ]</span>
<span class="gp">... </span><span class="s2">another = val</span>
<span class="gp">... </span><span class="s2">&quot;&quot;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">typical</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">typical</span><span class="o">.</span><span class="n">read_string</span><span class="p">(</span><span class="n">config</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">typical</span><span class="o">.</span><span class="n">sections</span><span class="p">()</span>
<span class="go">[&#39;Section 1&#39;, &#39;  Section 2  &#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">custom</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">custom</span><span class="o">.</span><span class="n">SECTCRE</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;\[ *(?P&lt;header&gt;[^]]+?) *\]&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">custom</span><span class="o">.</span><span class="n">read_string</span><span class="p">(</span><span class="n">config</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">custom</span><span class="o">.</span><span class="n">sections</span><span class="p">()</span>
<span class="go">[&#39;Section 1&#39;, &#39;Section 2&#39;]</span>
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>虽然 ConfigParser 对象也使用 <code class="docutils literal notranslate"><span class="pre">OPTCRE</span></code> 属性来识别选项行，但并不推荐重载它，因为这会与构造器选项 <em>allow_no_value</em> 和 <em>delimiters</em> 产生冲突。</p>
</div>
</dd></dl>

</div>
<div class="section" id="legacy-api-examples">
<h2>旧式 API 示例<a class="headerlink" href="#legacy-api-examples" title="永久链接至标题">¶</a></h2>
<p>主要出于向下兼容性的考虑，<a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">configparser</span></code></a> 还提供了一种采用显式 <code class="docutils literal notranslate"><span class="pre">get</span></code>/<code class="docutils literal notranslate"><span class="pre">set</span></code> 方法的旧式 API。 虽然以下介绍的方法存在有效的用例，但对于新项目仍建议采用映射协议访问。 旧式 API 在多数时候都更复杂、更底层并且完全违反直觉。</p>
<p>一个写入配置文件的示例:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">configparser</span>

<span class="n">config</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">RawConfigParser</span><span class="p">()</span>

<span class="c1"># Please note that using RawConfigParser&#39;s set functions, you can assign</span>
<span class="c1"># non-string values to keys internally, but will receive an error when</span>
<span class="c1"># attempting to write to a file or when you get it in non-raw mode. Setting</span>
<span class="c1"># values using the mapping protocol or ConfigParser&#39;s set() does not allow</span>
<span class="c1"># such assignments to take place.</span>
<span class="n">config</span><span class="o">.</span><span class="n">add_section</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">)</span>
<span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;an_int&#39;</span><span class="p">,</span> <span class="s1">&#39;15&#39;</span><span class="p">)</span>
<span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;a_bool&#39;</span><span class="p">,</span> <span class="s1">&#39;true&#39;</span><span class="p">)</span>
<span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;a_float&#39;</span><span class="p">,</span> <span class="s1">&#39;3.1415&#39;</span><span class="p">)</span>
<span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;baz&#39;</span><span class="p">,</span> <span class="s1">&#39;fun&#39;</span><span class="p">)</span>
<span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="s1">&#39;Python&#39;</span><span class="p">)</span>
<span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="s1">&#39;</span><span class="si">%(bar)s</span><span class="s1"> is </span><span class="si">%(baz)s</span><span class="s1">!&#39;</span><span class="p">)</span>

<span class="c1"># Writing our configuration file to &#39;example.cfg&#39;</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;example.cfg&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">configfile</span><span class="p">:</span>
    <span class="n">config</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">configfile</span><span class="p">)</span>
</pre></div>
</div>
<p>一个再次读取配置文件的示例:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">configparser</span>

<span class="n">config</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">RawConfigParser</span><span class="p">()</span>
<span class="n">config</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="s1">&#39;example.cfg&#39;</span><span class="p">)</span>

<span class="c1"># getfloat() raises an exception if the value is not a float</span>
<span class="c1"># getint() and getboolean() also do this for their respective types</span>
<span class="n">a_float</span> <span class="o">=</span> <span class="n">config</span><span class="o">.</span><span class="n">getfloat</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;a_float&#39;</span><span class="p">)</span>
<span class="n">an_int</span> <span class="o">=</span> <span class="n">config</span><span class="o">.</span><span class="n">getint</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;an_int&#39;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">a_float</span> <span class="o">+</span> <span class="n">an_int</span><span class="p">)</span>

<span class="c1"># Notice that the next output does not interpolate &#39;%(bar)s&#39; or &#39;%(baz)s&#39;.</span>
<span class="c1"># This is because we are using a RawConfigParser().</span>
<span class="k">if</span> <span class="n">config</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;a_bool&#39;</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>要获取插值，请使用 <a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">configparser</span>

<span class="n">cfg</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span>
<span class="n">cfg</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="s1">&#39;example.cfg&#39;</span><span class="p">)</span>

<span class="c1"># Set the optional *raw* argument of get() to True if you wish to disable</span>
<span class="c1"># interpolation in a single get operation.</span>
<span class="nb">print</span><span class="p">(</span><span class="n">cfg</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="n">raw</span><span class="o">=</span><span class="kc">False</span><span class="p">))</span>  <span class="c1"># -&gt; &quot;Python is fun!&quot;</span>
<span class="nb">print</span><span class="p">(</span><span class="n">cfg</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="n">raw</span><span class="o">=</span><span class="kc">True</span><span class="p">))</span>   <span class="c1"># -&gt; &quot;%(bar)s is %(baz)s!&quot;</span>

<span class="c1"># The optional *vars* argument is a dict with members that will take</span>
<span class="c1"># precedence in interpolation.</span>
<span class="nb">print</span><span class="p">(</span><span class="n">cfg</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="nb">vars</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;bar&#39;</span><span class="p">:</span> <span class="s1">&#39;Documentation&#39;</span><span class="p">,</span>
                                       <span class="s1">&#39;baz&#39;</span><span class="p">:</span> <span class="s1">&#39;evil&#39;</span><span class="p">}))</span>

<span class="c1"># The optional *fallback* argument can be used to provide a fallback value</span>
<span class="nb">print</span><span class="p">(</span><span class="n">cfg</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">))</span>
      <span class="c1"># -&gt; &quot;Python is fun!&quot;</span>

<span class="nb">print</span><span class="p">(</span><span class="n">cfg</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="n">fallback</span><span class="o">=</span><span class="s1">&#39;Monty is not.&#39;</span><span class="p">))</span>
      <span class="c1"># -&gt; &quot;Python is fun!&quot;</span>

<span class="nb">print</span><span class="p">(</span><span class="n">cfg</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;monster&#39;</span><span class="p">,</span> <span class="n">fallback</span><span class="o">=</span><span class="s1">&#39;No such things as monsters.&#39;</span><span class="p">))</span>
      <span class="c1"># -&gt; &quot;No such things as monsters.&quot;</span>

<span class="c1"># A bare print(cfg.get(&#39;Section1&#39;, &#39;monster&#39;)) would raise NoOptionError</span>
<span class="c1"># but we can also use:</span>

<span class="nb">print</span><span class="p">(</span><span class="n">cfg</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;monster&#39;</span><span class="p">,</span> <span class="n">fallback</span><span class="o">=</span><span class="kc">None</span><span class="p">))</span>
      <span class="c1"># -&gt; None</span>
</pre></div>
</div>
<p>默认值在两种类型的 ConfigParser 中均可用。 它们将在当某个选项未在别处定义时被用于插值。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">configparser</span>

<span class="c1"># New instance with &#39;bar&#39; and &#39;baz&#39; defaulting to &#39;Life&#39; and &#39;hard&#39; each</span>
<span class="n">config</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">({</span><span class="s1">&#39;bar&#39;</span><span class="p">:</span> <span class="s1">&#39;Life&#39;</span><span class="p">,</span> <span class="s1">&#39;baz&#39;</span><span class="p">:</span> <span class="s1">&#39;hard&#39;</span><span class="p">})</span>
<span class="n">config</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="s1">&#39;example.cfg&#39;</span><span class="p">)</span>

<span class="nb">print</span><span class="p">(</span><span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">))</span>     <span class="c1"># -&gt; &quot;Python is fun!&quot;</span>
<span class="n">config</span><span class="o">.</span><span class="n">remove_option</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="n">config</span><span class="o">.</span><span class="n">remove_option</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;baz&#39;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">))</span>     <span class="c1"># -&gt; &quot;Life is hard!&quot;</span>
</pre></div>
</div>
</div>
<div class="section" id="configparser-objects">
<span id="id11"></span><h2>ConfigParser 对象<a class="headerlink" href="#configparser-objects" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="configparser.ConfigParser">
<em class="property">class </em><code class="sig-prename descclassname">configparser.</code><code class="sig-name descname">ConfigParser</code><span class="sig-paren">(</span><em class="sig-param">defaults=None</em>, <em class="sig-param">dict_type=collections.OrderedDict</em>, <em class="sig-param">allow_no_value=False</em>, <em class="sig-param">delimiters=('='</em>, <em class="sig-param">':')</em>, <em class="sig-param">comment_prefixes=('#'</em>, <em class="sig-param">';')</em>, <em class="sig-param">inline_comment_prefixes=None</em>, <em class="sig-param">strict=True</em>, <em class="sig-param">empty_lines_in_values=True</em>, <em class="sig-param">default_section=configparser.DEFAULTSECT</em>, <em class="sig-param">interpolation=BasicInterpolation()</em>, <em class="sig-param">converters={}</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser" title="永久链接至目标">¶</a></dt>
<dd><p>主配置解析器。 当给定 <em>defaults</em> 时，它会被初始化为包含固有默认值的字典。 当给定 <em>dict_type</em> 时，它将被用来创建包含节、节中的选项以及默认值的字典。</p>
<p>当给定 <em>delimiters</em> 时，它会被用作分隔键与值的子字符串的集合。 当给定 <em>comment_prefixes</em> 时，它将被用作在否则为空行的注释的前缀子字符串的集合。 注释可以被缩进。 当给定 <em>inline_comment_prefixes</em> 时，它将被用作非空行的注释的前缀子字符串的集合。</p>
<p>当 <em>strict</em> 为 <code class="docutils literal notranslate"><span class="pre">True</span></code> (默认值) 时，解析器在从单个源（文件、字符串或字典）读取时将不允许任何节或选项出现重复，否则会引发 <a class="reference internal" href="#configparser.DuplicateSectionError" title="configparser.DuplicateSectionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DuplicateSectionError</span></code></a> 或 <a class="reference internal" href="#configparser.DuplicateOptionError" title="configparser.DuplicateOptionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DuplicateOptionError</span></code></a>。 当 <em>empty_lines_in_values</em> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code> (默认值: <code class="docutils literal notranslate"><span class="pre">True</span></code>) 时，每个空行均表示一个选项的结束。 在其他情况下，一个多行选项内部的空行会被保留为值的一部分。 当 <em>allow_no_value</em> 为 <code class="docutils literal notranslate"><span class="pre">True</span></code> (默认值: <code class="docutils literal notranslate"><span class="pre">False</span></code>) 时，将接受没有值的选项；此种选项的值将为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 并且它们会以不带末尾分隔符的形式被序列化。</p>
<p>当给定 <em>default_section</em> 时，它将指定存放其他节的默认值和用于插值的特殊节的名称 (通常命名为 <code class="docutils literal notranslate"><span class="pre">&quot;DEFAULT&quot;</span></code>)。 该值可通过使用 <code class="docutils literal notranslate"><span class="pre">default_section</span></code> 实例属性在运行时被读取或修改。</p>
<p>插值行为可通过给出 <em>interpolation</em> 参数提供自定义处理程序的方式来定制。 <code class="docutils literal notranslate"><span class="pre">None</span></code> 可用来完全禁用插值，<code class="docutils literal notranslate"><span class="pre">ExtendedInterpolation()</span></code> 提供了一种更高级的变体形式，它的设计受到了 <code class="docutils literal notranslate"><span class="pre">zc.buildout</span></code> 的启发。 有关该主题的更多信息请参见 <a class="reference external" href="#interpolation-of-values">专门的文档章节</a>。</p>
<p>插值中使用的所有选项名称将像任何其他选项名称引用一样通过 <a class="reference internal" href="#configparser.ConfigParser.optionxform" title="configparser.ConfigParser.optionxform"><code class="xref py py-meth docutils literal notranslate"><span class="pre">optionxform()</span></code></a> 方法来传递。 例如，使用 <a class="reference internal" href="#configparser.ConfigParser.optionxform" title="configparser.ConfigParser.optionxform"><code class="xref py py-meth docutils literal notranslate"><span class="pre">optionxform()</span></code></a> 的默认实现（它会将选项名称转换为小写形式）时，值 <code class="docutils literal notranslate"><span class="pre">foo</span> <span class="pre">%(bar)s</span></code> 和 <code class="docutils literal notranslate"><span class="pre">foo</span> <span class="pre">%(BAR)s</span></code> 是等价的。</p>
<p>当给定 <em>converters</em> 时，它应当为一个字典，其中每个键代表一个类型转换器的名称而每个值则为实现从字符串到目标数据类型的转换的可调用对象。 每个转换器会获得其在解析器对象和节代理上对应的 <code class="xref py py-meth docutils literal notranslate"><span class="pre">get*()</span></code> 方法。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.1 版更改: </span>默认的 <em>dict_type</em> 为 <a class="reference internal" href="collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.OrderedDict</span></code></a>。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.2 版更改: </span>添加了 <em>allow_no_value</em>, <em>delimiters</em>, <em>comment_prefixes</em>, <em>strict</em>, <em>empty_lines_in_values</em>, <em>default_section</em> 以及 <em>interpolation</em>。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>添加了 <em>converters</em> 参数。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span><em>defaults</em> 参数会通过 <a class="reference internal" href="#configparser.ConfigParser.read_dict" title="configparser.ConfigParser.read_dict"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read_dict()</span></code></a> 来读取，提供全解析器范围内一致的行为：非字符串类型的键和值会被隐式地转换为字符串。</p>
</div>
<dl class="method">
<dt id="configparser.ConfigParser.defaults">
<code class="sig-name descname">defaults</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.defaults" title="永久链接至目标">¶</a></dt>
<dd><p>返回包含实例范围内默认值的字典。</p>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.sections">
<code class="sig-name descname">sections</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.sections" title="永久链接至目标">¶</a></dt>
<dd><p>返回可用节的列表；<em>default section</em> 不包括在该列表中。</p>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.add_section">
<code class="sig-name descname">add_section</code><span class="sig-paren">(</span><em class="sig-param">section</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.add_section" title="永久链接至目标">¶</a></dt>
<dd><p>向实例添加一个名为 <em>section</em> 的节。 如果给定名称的节已存在，将会引发 <a class="reference internal" href="#configparser.DuplicateSectionError" title="configparser.DuplicateSectionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DuplicateSectionError</span></code></a>。 如果转入了 <em>default section</em> 名称，则会引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。 节名称必须为字符串；如果不是则会引发 <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.2 版更改: </span>非字符串的节名称将引发 <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.has_section">
<code class="sig-name descname">has_section</code><span class="sig-paren">(</span><em class="sig-param">section</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.has_section" title="永久链接至目标">¶</a></dt>
<dd><p>指明相应名称的 <em>section</em> 是否存在于配置中。 <em>default section</em> 不包含在内。</p>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.options">
<code class="sig-name descname">options</code><span class="sig-paren">(</span><em class="sig-param">section</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.options" title="永久链接至目标">¶</a></dt>
<dd><p>返回指定 <em>section</em> 中可用选项的列表。</p>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.has_option">
<code class="sig-name descname">has_option</code><span class="sig-paren">(</span><em class="sig-param">section</em>, <em class="sig-param">option</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.has_option" title="永久链接至目标">¶</a></dt>
<dd><p>如果给定的 <em>section</em> 存在并且包含给定的 <em>option</em> 则返回 <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>；否则返回 <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>。 如果指定的 <em>section</em> 为 <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> 或空字符串，则会使用 DEFAULT。</p>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.read">
<code class="sig-name descname">read</code><span class="sig-paren">(</span><em class="sig-param">filenames</em>, <em class="sig-param">encoding=None</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.read" title="永久链接至目标">¶</a></dt>
<dd><p>尝试读取并解析一个包含文件名的可迭代对象，返回一个被成功解析的文件名列表。</p>
<p>如果 <em>filenames</em> 为字符串、<a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象或 <a class="reference internal" href="../glossary.html#term-path-like-object"><span class="xref std std-term">path-like object</span></a>，它会被当作单个文件来处理。 如果 <em>filenames</em> 中名称对应的某个文件无法被打开，该文件将被忽略。 这样的设计使得你可以指定包含多个潜在配置文件位置的可迭代对象（例如当前目录、用户家目录以及某个系统级目录），存在于该可迭代对象中的所有配置文件都将被读取。</p>
<p>如果名称对应的文件全都不存在，则 <a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> 实例将包含一个空数据集。 一个要求从文件加载初始值的应用应当在调用 <a class="reference internal" href="#configparser.ConfigParser.read" title="configparser.ConfigParser.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> 来获取任何可选文件之前使用 <a class="reference internal" href="#configparser.ConfigParser.read_file" title="configparser.ConfigParser.read_file"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read_file()</span></code></a> 来加载所要求的一个或多个文件:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">configparser</span><span class="o">,</span> <span class="nn">os</span>

<span class="n">config</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span>
<span class="n">config</span><span class="o">.</span><span class="n">read_file</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="s1">&#39;defaults.cfg&#39;</span><span class="p">))</span>
<span class="n">config</span><span class="o">.</span><span class="n">read</span><span class="p">([</span><span class="s1">&#39;site.cfg&#39;</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">expanduser</span><span class="p">(</span><span class="s1">&#39;~/.myapp.cfg&#39;</span><span class="p">)],</span>
            <span class="n">encoding</span><span class="o">=</span><span class="s1">&#39;cp1250&#39;</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能: </span><em>encoding</em> 形参。 在之前的版本中，所有文件都将使用 <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> 的默认编码格式来读取。</p>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.6.1 新版功能: </span><em>filenames</em> 形参接受一个 <a class="reference internal" href="../glossary.html#term-path-like-object"><span class="xref std std-term">path-like object</span></a>。</p>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能: </span><em>filenames</em> 形参接受一个 <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.read_file">
<code class="sig-name descname">read_file</code><span class="sig-paren">(</span><em class="sig-param">f</em>, <em class="sig-param">source=None</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.read_file" title="永久链接至目标">¶</a></dt>
<dd><p>从 <em>f</em> 读取并解析配置数据，它必须是一个产生 Unicode 字符串的可迭代对象（例如以文本模式打开的文件）。</p>
<p>可选参数 <em>source</em> 指定要读取的文件名称。 如果未给出并且 <em>f</em> 具有 <code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code> 属性，则该属性会被用作 <em>source</em>；默认值为 <code class="docutils literal notranslate"><span class="pre">'&lt;???&gt;'</span></code>。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能: </span>替代 <a class="reference internal" href="#configparser.ConfigParser.readfp" title="configparser.ConfigParser.readfp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readfp()</span></code></a>。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.read_string">
<code class="sig-name descname">read_string</code><span class="sig-paren">(</span><em class="sig-param">string</em>, <em class="sig-param">source='&lt;string&gt;'</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.read_string" title="永久链接至目标">¶</a></dt>
<dd><p>从字符串中解析配置数据。</p>
<p>可选参数 <em>source</em> 指定一个所传入字符串的上下文专属名称。 如果未给出，则会使用 <code class="docutils literal notranslate"><span class="pre">'&lt;string&gt;'</span></code>。 这通常应为一个文件系统路径或 URL。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.read_dict">
<code class="sig-name descname">read_dict</code><span class="sig-paren">(</span><em class="sig-param">dictionary</em>, <em class="sig-param">source='&lt;dict&gt;'</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.read_dict" title="永久链接至目标">¶</a></dt>
<dd><p>从任意一个提供了类似于字典的 <code class="docutils literal notranslate"><span class="pre">items()</span></code> 方法的对象加载配置。 键为节名称，值为包含节中所出现的键和值的字典。 如果所用的字典类型会保留顺序，则节和其中的键将按顺序加入。 值会被自动转换为字符串。</p>
<p>可选参数 <em>source</em> 指定一个所传入字曲的上下文专属名称。 如果未给出，则会使用 <code class="docutils literal notranslate"><span class="pre">&lt;dict&gt;</span></code>。</p>
<p>此方法可被用于在解析器之间拷贝状态。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.get">
<code class="sig-name descname">get</code><span class="sig-paren">(</span><em class="sig-param">section</em>, <em class="sig-param">option</em>, <em class="sig-param">*</em>, <em class="sig-param">raw=False</em>, <em class="sig-param">vars=None</em><span class="optional">[</span>, <em class="sig-param">fallback</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.get" title="永久链接至目标">¶</a></dt>
<dd><p>获取指定名称的 <em>section</em> 的一个 <em>option</em> 的值。 如果提供了 <em>vars</em>，则它必须为一个字典。 <em>option</em> 的查找顺序为 <em>vars*（如果有提供）、*section</em> 以及 <em>DEFAULTSECT</em>。 如果未找到该键并且提供了 <em>fallback</em>，则它会被用作回退值。 可以提供 <code class="docutils literal notranslate"><span class="pre">None</span></code> 作为 <em>fallback</em> 值。</p>
<p>所有 <code class="docutils literal notranslate"><span class="pre">'%'</span></code> 插值会在返回值中被展开，除非 <em>raw</em> 参数为真值。 插值键所使用的值会按与选项相同的方式来查找。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.2 版更改: </span><em>raw</em>, <em>vars</em> 和 <em>fallback</em> 都是仅限关键字参数，以防止用户试图使用第三个参数作业为 <em>fallback</em> 回退值（特别是在使用映射 协议的时候）。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.getint">
<code class="sig-name descname">getint</code><span class="sig-paren">(</span><em class="sig-param">section</em>, <em class="sig-param">option</em>, <em class="sig-param">*</em>, <em class="sig-param">raw=False</em>, <em class="sig-param">vars=None</em><span class="optional">[</span>, <em class="sig-param">fallback</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.getint" title="永久链接至目标">¶</a></dt>
<dd><p>将在 <em>section</em> 中指定的 <em>option</em> 强制转换为整数的便捷方法。 参见 <a class="reference internal" href="#configparser.ConfigParser.get" title="configparser.ConfigParser.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> 获取对于 <em>raw</em>, <em>vars</em> 和 <em>fallback</em> 的解释。</p>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.getfloat">
<code class="sig-name descname">getfloat</code><span class="sig-paren">(</span><em class="sig-param">section</em>, <em class="sig-param">option</em>, <em class="sig-param">*</em>, <em class="sig-param">raw=False</em>, <em class="sig-param">vars=None</em><span class="optional">[</span>, <em class="sig-param">fallback</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.getfloat" title="永久链接至目标">¶</a></dt>
<dd><p>将在 <em>section</em> 中指定的 <em>option</em> 强制转换为浮点数的便捷方法。 参见 <a class="reference internal" href="#configparser.ConfigParser.get" title="configparser.ConfigParser.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> 获取对于 <em>raw</em>, <em>vars</em> 和 <em>fallback</em> 的解释。</p>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.getboolean">
<code class="sig-name descname">getboolean</code><span class="sig-paren">(</span><em class="sig-param">section</em>, <em class="sig-param">option</em>, <em class="sig-param">*</em>, <em class="sig-param">raw=False</em>, <em class="sig-param">vars=None</em><span class="optional">[</span>, <em class="sig-param">fallback</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.getboolean" title="永久链接至目标">¶</a></dt>
<dd><p>将在指定 <em>section</em> 中的 <em>option</em> 强制转换为布尔值的便捷方法。 请注意选项所接受的值为 <code class="docutils literal notranslate"><span class="pre">'1'</span></code>, <code class="docutils literal notranslate"><span class="pre">'yes'</span></code>, <code class="docutils literal notranslate"><span class="pre">'true'</span></code> 和 <code class="docutils literal notranslate"><span class="pre">'on'</span></code>，它们会使得此方法返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>，以及 <code class="docutils literal notranslate"><span class="pre">'0'</span></code>, <code class="docutils literal notranslate"><span class="pre">'no'</span></code>, <code class="docutils literal notranslate"><span class="pre">'false'</span></code> 和 <code class="docutils literal notranslate"><span class="pre">'off'</span></code>，它们会使得此方法返回 <code class="docutils literal notranslate"><span class="pre">False</span></code>。 这些字符串值会以对大小写不敏感的方式被检测。 任何其他值都将导致引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。 参见 <a class="reference internal" href="#configparser.ConfigParser.get" title="configparser.ConfigParser.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> 获取对于 <em>raw</em>, <em>vars</em> 和 <em>fallback</em> 的解释。</p>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.items">
<code class="sig-name descname">items</code><span class="sig-paren">(</span><em class="sig-param">raw=False</em>, <em class="sig-param">vars=None</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.items" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">items</code><span class="sig-paren">(</span><em class="sig-param">section</em>, <em class="sig-param">raw=False</em>, <em class="sig-param">vars=None</em><span class="sig-paren">)</span></dt>
<dd><p>当未给出 <em>section</em> 时，将返回由 <em>section_name</em>, <em>section_proxy</em> 对组成的列表，包括 DEFAULTSECT。</p>
<p>在其他情况下，将返回给定的 <em>section</em> 中的 option 的 <em>name</em>, <em>value</em> 对组成的列表。 可选参数具有与 <a class="reference internal" href="#configparser.ConfigParser.get" title="configparser.ConfigParser.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> 方法的参数相同的含义。</p>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.set">
<code class="sig-name descname">set</code><span class="sig-paren">(</span><em class="sig-param">section</em>, <em class="sig-param">option</em>, <em class="sig-param">value</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.set" title="永久链接至目标">¶</a></dt>
<dd><p>如果给定的节存在，则将所给出的选项设为指定的值；在其他情况下将引发 <a class="reference internal" href="#configparser.NoSectionError" title="configparser.NoSectionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NoSectionError</span></code></a>。 <em>option</em> 和 <em>value</em> 必须为字符串；如果不是则将引发 <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.write">
<code class="sig-name descname">write</code><span class="sig-paren">(</span><em class="sig-param">fileobject</em>, <em class="sig-param">space_around_delimiters=True</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.write" title="永久链接至目标">¶</a></dt>
<dd><p>将配置的表示形式写入指定的 <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a>，该对象必须以文本模式打开（接受字符串）。 此表示形式可由将来的 <a class="reference internal" href="#configparser.ConfigParser.read" title="configparser.ConfigParser.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> 调用进行解析。 如果 <em>space_around_delimiters</em> 为真值，键和值之前的分隔符两边将加上空格。</p>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.remove_option">
<code class="sig-name descname">remove_option</code><span class="sig-paren">(</span><em class="sig-param">section</em>, <em class="sig-param">option</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.remove_option" title="永久链接至目标">¶</a></dt>
<dd><p>将指定的 <em>option</em> 从指定的 <em>section</em> 中移除。 如果指定的节不存在则会引发 <a class="reference internal" href="#configparser.NoSectionError" title="configparser.NoSectionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NoSectionError</span></code></a>。 如果要移除的选项存在则返回 <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>；在其他情况下将返回 <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.remove_section">
<code class="sig-name descname">remove_section</code><span class="sig-paren">(</span><em class="sig-param">section</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.remove_section" title="永久链接至目标">¶</a></dt>
<dd><p>从配置中移除指定的 <em>section</em>。 如果指定的节确实存在则返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>。 在其他情况下将返回 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
</dd></dl>

<dl class="method">
<dt>
<code class="sig-name descname">optionxform</code><span class="sig-paren">(</span><em class="sig-param">option</em><span class="sig-paren">)</span></dt>
<dd><p>将选项名 <em>option</em> 转换为输入文件中的形式或客户端代码所传入的应当在内部结构中使用的形式。 默认实现将返回 <em>option</em> 的小写形式版本；子类可以重载此行为，或者客户端代码也可以在实例上设置一个具有此名称的属性来影响此行为。</p>
<p>你不需要子类化解析器来使用此方法，你也可以在一个实例上设置它，或使用一个接受字符串参数并返回字符串的函数。 例如将它设为 <code class="docutils literal notranslate"><span class="pre">str</span></code> 将使得选项名称变得大小写敏感:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">cfgparser</span> <span class="o">=</span> <span class="n">ConfigParser</span><span class="p">()</span>
<span class="n">cfgparser</span><span class="o">.</span><span class="n">optionxform</span> <span class="o">=</span> <span class="nb">str</span>
</pre></div>
</div>
<p>请注意当读取配置文件时，选项名称两边的空格将在调用 <a class="reference internal" href="#configparser.ConfigParser.optionxform" title="configparser.ConfigParser.optionxform"><code class="xref py py-meth docutils literal notranslate"><span class="pre">optionxform()</span></code></a> 之前被去除。</p>
</dd></dl>

<dl class="method">
<dt id="configparser.ConfigParser.readfp">
<code class="sig-name descname">readfp</code><span class="sig-paren">(</span><em class="sig-param">fp</em>, <em class="sig-param">filename=None</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.ConfigParser.readfp" title="永久链接至目标">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified deprecated">3.2 版后已移除: </span>使用 <a class="reference internal" href="#configparser.ConfigParser.read_file" title="configparser.ConfigParser.read_file"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read_file()</span></code></a> 来代替。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.2 版更改: </span><a class="reference internal" href="#configparser.ConfigParser.readfp" title="configparser.ConfigParser.readfp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readfp()</span></code></a> 现在将在 <em>fp</em> 上执行迭代而不是调用 <code class="docutils literal notranslate"><span class="pre">fp.readline()</span></code>。</p>
</div>
<p>对于调用 <a class="reference internal" href="#configparser.ConfigParser.readfp" title="configparser.ConfigParser.readfp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readfp()</span></code></a> 时传入不支持迭代的参数的现有代码，可以在文件类对象外使用以下生成器作为包装器:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">readline_generator</span><span class="p">(</span><span class="n">fp</span><span class="p">):</span>
    <span class="n">line</span> <span class="o">=</span> <span class="n">fp</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
    <span class="k">while</span> <span class="n">line</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">line</span>
        <span class="n">line</span> <span class="o">=</span> <span class="n">fp</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
</pre></div>
</div>
<p>不再使用 <code class="docutils literal notranslate"><span class="pre">parser.readfp(fp)</span></code> 而是改用 <code class="docutils literal notranslate"><span class="pre">parser.read_file(readline_generator(fp))</span></code>。</p>
</dd></dl>

</dd></dl>

<dl class="data">
<dt id="configparser.MAX_INTERPOLATION_DEPTH">
<code class="sig-prename descclassname">configparser.</code><code class="sig-name descname">MAX_INTERPOLATION_DEPTH</code><a class="headerlink" href="#configparser.MAX_INTERPOLATION_DEPTH" title="永久链接至目标">¶</a></dt>
<dd><p>当 <em>raw</em> 形参为假值时 <code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code> 所采用的递归插值的最大深度。 这只在使用默认的 <em>interpolation</em> 时会起作用。</p>
</dd></dl>

</div>
<div class="section" id="rawconfigparser-objects">
<span id="id13"></span><h2>RawConfigParser 对象<a class="headerlink" href="#rawconfigparser-objects" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="configparser.RawConfigParser">
<em class="property">class </em><code class="sig-prename descclassname">configparser.</code><code class="sig-name descname">RawConfigParser</code><span class="sig-paren">(</span><em class="sig-param">defaults=None</em>, <em class="sig-param">dict_type=collections.OrderedDict</em>, <em class="sig-param">allow_no_value=False</em>, <em class="sig-param">*</em>, <em class="sig-param">delimiters=('='</em>, <em class="sig-param">':')</em>, <em class="sig-param">comment_prefixes=('#'</em>, <em class="sig-param">';')</em>, <em class="sig-param">inline_comment_prefixes=None</em>, <em class="sig-param">strict=True</em>, <em class="sig-param">empty_lines_in_values=True</em>, <em class="sig-param">default_section=configparser.DEFAULTSECT</em><span class="optional">[</span>, <em class="sig-param">interpolation</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#configparser.RawConfigParser" title="永久链接至目标">¶</a></dt>
<dd><p>旧式 <a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a>。 它默认禁用插值并且允许通过不安全的 <code class="docutils literal notranslate"><span class="pre">add_section</span></code> 和 <code class="docutils literal notranslate"><span class="pre">set</span></code> 方法以及旧式 <code class="docutils literal notranslate"><span class="pre">defaults=</span></code> 关键字参数处理来设置非字符串的节名、选项名和值。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>考虑改用 <a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a>，它会检查内部保存的值的类型。 如果你不想要插值，你可以使用 <code class="docutils literal notranslate"><span class="pre">ConfigParser(interpolation=None)</span></code>。</p>
</div>
<dl class="method">
<dt id="configparser.RawConfigParser.add_section">
<code class="sig-name descname">add_section</code><span class="sig-paren">(</span><em class="sig-param">section</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.RawConfigParser.add_section" title="永久链接至目标">¶</a></dt>
<dd><p>向实例添加一个名为 <em>section</em> 的节。 如果给定名称的节已存在，将会引发 <a class="reference internal" href="#configparser.DuplicateSectionError" title="configparser.DuplicateSectionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DuplicateSectionError</span></code></a>。 如果传入了 <em>default section</em> 名称，则会引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。</p>
<p>不检查 <em>section</em> 以允许用户创建以非字符串命名的节。 此行为已不受支持并可能导致内部错误。</p>
</dd></dl>

<dl class="method">
<dt id="configparser.RawConfigParser.set">
<code class="sig-name descname">set</code><span class="sig-paren">(</span><em class="sig-param">section</em>, <em class="sig-param">option</em>, <em class="sig-param">value</em><span class="sig-paren">)</span><a class="headerlink" href="#configparser.RawConfigParser.set" title="永久链接至目标">¶</a></dt>
<dd><p>如果给定的节存在，则将给定的选项设为指定的值；在其他情况下将引发 <a class="reference internal" href="#configparser.NoSectionError" title="configparser.NoSectionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NoSectionError</span></code></a>。 虽然可能使用 <a class="reference internal" href="#configparser.RawConfigParser" title="configparser.RawConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawConfigParser</span></code></a> (或使用 <a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> 并将 <em>raw</em> 形参设为真值) 以便实现非字符串值的 <em>internal</em> 存储，但是完整功能（包括插值和输出到文件）只能使用字符串值来实现。</p>
<p>此方法允许用户在内部将非字符串值赋给键。 此行为已不受支持并会在尝试写入到文件或在非原始模式下获取数据时导致错误。 <strong>请使用映射协议 API</strong>，它不允许出现这样的赋值。</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="exceptions">
<h2>异常<a class="headerlink" href="#exceptions" title="永久链接至标题">¶</a></h2>
<dl class="exception">
<dt id="configparser.Error">
<em class="property">exception </em><code class="sig-prename descclassname">configparser.</code><code class="sig-name descname">Error</code><a class="headerlink" href="#configparser.Error" title="永久链接至目标">¶</a></dt>
<dd><p>所有其他 <a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">configparser</span></code></a> 异常的基类。</p>
</dd></dl>

<dl class="exception">
<dt id="configparser.NoSectionError">
<em class="property">exception </em><code class="sig-prename descclassname">configparser.</code><code class="sig-name descname">NoSectionError</code><a class="headerlink" href="#configparser.NoSectionError" title="永久链接至目标">¶</a></dt>
<dd><p>当找不到指定节时引发的异常。</p>
</dd></dl>

<dl class="exception">
<dt id="configparser.DuplicateSectionError">
<em class="property">exception </em><code class="sig-prename descclassname">configparser.</code><code class="sig-name descname">DuplicateSectionError</code><a class="headerlink" href="#configparser.DuplicateSectionError" title="永久链接至目标">¶</a></dt>
<dd><p>当调用 <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_section()</span></code> 时传入已存在的节名称，或者在严格解析器中当单个输入文件、字符串或字典内出现重复的节时引发的异常。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能: </span>将可选的 <code class="docutils literal notranslate"><span class="pre">source</span></code> 和 <code class="docutils literal notranslate"><span class="pre">lineno</span></code> 属性和参数添加到 <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>。</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="configparser.DuplicateOptionError">
<em class="property">exception </em><code class="sig-prename descclassname">configparser.</code><code class="sig-name descname">DuplicateOptionError</code><a class="headerlink" href="#configparser.DuplicateOptionError" title="永久链接至目标">¶</a></dt>
<dd><p>当单个选项在从单个文件、字符串或字典读取时出现两次时引发的异常。 这会捕获拼写错误和大小写敏感相关的错误，例如一个字典可能包含两个键分别代表同一个大小写不敏感的配置键。</p>
</dd></dl>

<dl class="exception">
<dt id="configparser.NoOptionError">
<em class="property">exception </em><code class="sig-prename descclassname">configparser.</code><code class="sig-name descname">NoOptionError</code><a class="headerlink" href="#configparser.NoOptionError" title="永久链接至目标">¶</a></dt>
<dd><p>当指定的选项未在指定的节中被找到时引发的异常。</p>
</dd></dl>

<dl class="exception">
<dt id="configparser.InterpolationError">
<em class="property">exception </em><code class="sig-prename descclassname">configparser.</code><code class="sig-name descname">InterpolationError</code><a class="headerlink" href="#configparser.InterpolationError" title="永久链接至目标">¶</a></dt>
<dd><p>当执行字符串插值发生问题时所引发的异常的基类。</p>
</dd></dl>

<dl class="exception">
<dt id="configparser.InterpolationDepthError">
<em class="property">exception </em><code class="sig-prename descclassname">configparser.</code><code class="sig-name descname">InterpolationDepthError</code><a class="headerlink" href="#configparser.InterpolationDepthError" title="永久链接至目标">¶</a></dt>
<dd><p>当字符串插值由于迭代次数超出 <a class="reference internal" href="#configparser.MAX_INTERPOLATION_DEPTH" title="configparser.MAX_INTERPOLATION_DEPTH"><code class="xref py py-const docutils literal notranslate"><span class="pre">MAX_INTERPOLATION_DEPTH</span></code></a> 而无法完成所引发的异常。 为 <a class="reference internal" href="#configparser.InterpolationError" title="configparser.InterpolationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InterpolationError</span></code></a> 的子类。</p>
</dd></dl>

<dl class="exception">
<dt id="configparser.InterpolationMissingOptionError">
<em class="property">exception </em><code class="sig-prename descclassname">configparser.</code><code class="sig-name descname">InterpolationMissingOptionError</code><a class="headerlink" href="#configparser.InterpolationMissingOptionError" title="永久链接至目标">¶</a></dt>
<dd><p>当从某个值引用的选项并不存在时引发的异常。 为 <a class="reference internal" href="#configparser.InterpolationError" title="configparser.InterpolationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InterpolationError</span></code></a> 的子类。</p>
</dd></dl>

<dl class="exception">
<dt id="configparser.InterpolationSyntaxError">
<em class="property">exception </em><code class="sig-prename descclassname">configparser.</code><code class="sig-name descname">InterpolationSyntaxError</code><a class="headerlink" href="#configparser.InterpolationSyntaxError" title="永久链接至目标">¶</a></dt>
<dd><p>当将要执行替换的源文本不符合要求的语法时引发的异常。 为 <a class="reference internal" href="#configparser.InterpolationError" title="configparser.InterpolationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InterpolationError</span></code></a> 的子类。</p>
</dd></dl>

<dl class="exception">
<dt id="configparser.MissingSectionHeaderError">
<em class="property">exception </em><code class="sig-prename descclassname">configparser.</code><code class="sig-name descname">MissingSectionHeaderError</code><a class="headerlink" href="#configparser.MissingSectionHeaderError" title="永久链接至目标">¶</a></dt>
<dd><p>当尝试解析一个不带节标头的文件时引发的异常。</p>
</dd></dl>

<dl class="exception">
<dt id="configparser.ParsingError">
<em class="property">exception </em><code class="sig-prename descclassname">configparser.</code><code class="sig-name descname">ParsingError</code><a class="headerlink" href="#configparser.ParsingError" title="永久链接至目标">¶</a></dt>
<dd><p>当尝试解析一个文件而发生错误时引发的异常。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.2 版更改: </span><code class="docutils literal notranslate"><span class="pre">filename</span></code> 属性和 <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> 参数被重命名为 <code class="docutils literal notranslate"><span class="pre">source</span></code> 以保持一致性。</p>
</div>
</dd></dl>

<p class="rubric">备注</p>
<dl class="footnote brackets">
<dt class="label" id="id14"><span class="brackets">1</span><span class="fn-backref">(<a href="#id1">1</a>,<a href="#id2">2</a>,<a href="#id3">3</a>,<a href="#id4">4</a>,<a href="#id5">5</a>,<a href="#id6">6</a>,<a href="#id7">7</a>,<a href="#id8">8</a>,<a href="#id9">9</a>,<a href="#id10">10</a>)</span></dt>
<dd><p>配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行为，请参阅 <a class="reference internal" href="#customizing-parser-behaviour">Customizing Parser Behaviour</a> 一节。</p>
</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">目录</a></h3>
  <ul>
<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">configparser</span></code> --- 配置文件解析器</a><ul>
<li><a class="reference internal" href="#quick-start">快速起步</a></li>
<li><a class="reference internal" href="#supported-datatypes">支持的数据类型</a></li>
<li><a class="reference internal" href="#fallback-values">回退值</a></li>
<li><a class="reference internal" href="#supported-ini-file-structure">受支持的 INI 文件结构</a></li>
<li><a class="reference internal" href="#interpolation-of-values">值的插入</a></li>
<li><a class="reference internal" href="#mapping-protocol-access">映射协议访问</a></li>
<li><a class="reference internal" href="#customizing-parser-behaviour">定制解析器行为</a></li>
<li><a class="reference internal" href="#legacy-api-examples">旧式 API 示例</a></li>
<li><a class="reference internal" href="#configparser-objects">ConfigParser 对象</a></li>
<li><a class="reference internal" href="#rawconfigparser-objects">RawConfigParser 对象</a></li>
<li><a class="reference internal" href="#exceptions">异常</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="csv.html"
                        title="上一章"><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code> --- CSV 文件读写</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="netrc.html"
                        title="下一章"><code class="xref py py-mod docutils literal notranslate"><span class="pre">netrc</span></code> --- netrc 文件处理</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">提交 Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.7/Doc/library/configparser.rst"
            rel="nofollow">显示源代码
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             >索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="netrc.html" title="netrc --- netrc 文件处理"
             >下一页</a> |</li>
        <li class="right" >
          <a href="csv.html" title="csv --- CSV 文件读写"
             >上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="fileformats.html" >文件格式</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">版权所有</a> 2001-2020, Python Software Foundation.
    <br />
    Python 软件基金会是一个非盈利组织。
    <a href="https://www.python.org/psf/donations/">请捐助。</a>
    <br />
    最后更新于 6月 29, 2020.
    <a href="../bugs.html">发现了问题</a>？
    <br />
    使用<a href="http://sphinx.pocoo.org/">Sphinx</a>2.3.1 创建。
    </div>

  </body>
</html>